<!-- 文件名: app/templates/progress.html -->
{% extends "base.html" %}

{% block title %}更新进度 - 社交媒体监控{% endblock %}

{% block page_title %}更新进度{% endblock %}

{% block content %}
<div class="card mb-4">
    <div class="card-header d-flex justify-content-between align-items-center">
        <h5 class="mb-0">实时进度</h5>
        <div>
            <span class="badge bg-secondary" id="status-badge">等待连接...</span>
            <button class="btn btn-sm btn-outline-secondary" onclick="clearLogs()">清空日志</button>
        </div>
    </div>
    <div class="card-body">
        <div class="border rounded p-3 bg-light" style="height: 400px; overflow-y: auto;" id="log-container">
            <div class="text-center text-muted py-5">
                等待更新开始...
            </div>
        </div>
    </div>
</div>

<div class="mb-4">
    <a href="/users" class="btn btn-primary">返回用户列表</a>
</div>
{% endblock %}

{% block scripts %}
<script>
    let socket;
    let clientId = '{{ client_id }}';
    let isConnected = false;
    let logs = [];
    const maxLogs = 100; // 最大日志显示数量

    // 连接WebSocket
    function connectWebSocket() {
        if (socket && socket.readyState !== WebSocket.CLOSED) {
            return; // 如果已经有连接，则不再创建
        }

        // 创建WebSocket连接
        socket = new WebSocket(`ws://${window.location.host}/ws/${clientId}`);

        // 连接打开
        socket.onopen = function (e) {
            console.log('WebSocket连接已建立');
            isConnected = true;
            updateStatusBadge('连接成功', 'success');
        };

        // 接收消息
        socket.onmessage = function (event) {
            const data = JSON.parse(event.data);
            handleProgressUpdate(data);
        };

        // 连接关闭
        socket.onclose = function (event) {
            if (isConnected) {
                console.log('WebSocket连接已关闭');
                isConnected = false;
                updateStatusBadge('连接断开', 'danger');

                // 尝试重新连接
                setTimeout(connectWebSocket, 3000);
            }
        };

        // 连接错误
        socket.onerror = function (error) {
            console.error('WebSocket错误:', error);
            updateStatusBadge('连接错误', 'danger');
            isConnected = false;

            // 尝试重新连接
            setTimeout(connectWebSocket, 5000);
        };
    }

    // 处理进度更新
    function handleProgressUpdate(data) {
        // 记录日志
        addLog(data);

        // 根据消息类型处理
        switch (data.type) {
            case 'start':
                updateStatusBadge('进行中', 'primary');
                break;

            case 'checking':
            case 'user_done':
                break;

            case 'update':
            case 'downloading':
            case 'processing':
                // 视频更新和下载进度
                break;

            case 'complete':
                updateStatusBadge('已完成', 'success');
                break;

            case 'error':
                addLog({type: 'error', message: data.message});
                break;
        }
    }

    // 更新状态徽章
    function updateStatusBadge(text, type) {
        const badge = document.getElementById('status-badge');
        badge.innerText = text;
        badge.className = `badge bg-${type}`;
    }

    // 添加日志
    function addLog(data) {
        // 日志时间戳
        const timestamp = new Date().toLocaleTimeString();

        // 根据类型设置样式
        let logClass = 'text-secondary';
        if (data.type === 'success') logClass = 'text-success';
        else if (data.type === 'error') logClass = 'text-danger';
        else if (data.type === 'warning') logClass = 'text-warning';
        else if (data.type === 'info') logClass = 'text-info';
        else if (data.type === 'update' || data.type === 'checking') logClass = 'text-primary';

        // 创建日志项
        const logItem = {
            timestamp: timestamp,
            message: data.message,
            class: logClass
        };

        // 添加到日志数组
        logs.unshift(logItem);

        // 限制日志数量
        if (logs.length > maxLogs) {
            logs = logs.slice(0, maxLogs);
        }

        // 更新显示
        renderLogs();
    }

    // 渲染日志
    function renderLogs() {
        const container = document.getElementById('log-container');

        if (logs.length === 0) {
            container.innerHTML = '<div class="text-center text-muted py-5">没有日志记录</div>';
            return;
        }

        let html = '';
        logs.forEach(log => {
            html += `<div class="log-item mb-1">
            <small class="text-muted">${log.timestamp}</small>
            <span class="${log.class}">${log.message}</span>
        </div>`;
        });

        container.innerHTML = html;
    }

    // 清空日志
    function clearLogs() {
        logs = [];
        renderLogs();
    }

    // 初始化
    document.addEventListener('DOMContentLoaded', function () {
        // 连接WebSocket
        connectWebSocket();

        // 预填充客户端ID（如果URL中有）
        const urlParams = new URLSearchParams(window.location.search);
        const urlClientId = urlParams.get('client_id');
        if (urlClientId) {
            clientId = urlClientId;
        }
    });
</script>
{% endblock %}